package com.photovoltaic.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photovoltaic.auth.entity.Permission;
import com.photovoltaic.auth.entity.Role;
import com.photovoltaic.auth.entity.User;
import com.photovoltaic.auth.security.services.UserDetailsImpl;
import com.photovoltaic.auth.service.OperationLogService;
import com.photovoltaic.auth.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/auth/users")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    private final OperationLogService operationLogService;
    
    @GetMapping
    @PreAuthorize("hasAuthority('user:list')")
    public ResponseEntity<Page<User>> getUsers(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            queryWrapper.like(User::getUsername, username);
        }
        
        Page<User> page = userService.page(new Page<>(current, size), queryWrapper);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "USER_QUERY",
                "查询用户列表",
                request.getRemoteAddr(),
                1
        );
        
        return ResponseEntity.ok(page);
    }
    
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('user:view')")
    public ResponseEntity<User> getUserById(@PathVariable Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(user);
    }
    
    @GetMapping("/{id}/roles")
    @PreAuthorize("hasAuthority('user:view')")
    public ResponseEntity<List<Role>> getUserRoles(@PathVariable Long id) {
        List<Role> roles = userService.getUserRoles(id);
        return ResponseEntity.ok(roles);
    }
    
    @GetMapping("/{id}/permissions")
    @PreAuthorize("hasAuthority('user:view')")
    public ResponseEntity<List<Permission>> getUserPermissions(@PathVariable Long id) {
        List<Permission> permissions = userService.getUserPermissions(id);
        return ResponseEntity.ok(permissions);
    }
    
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('user:edit')")
    public ResponseEntity<Map<String, Object>> updateUserStatus(
            @PathVariable Integer id,
            @RequestParam Integer status,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        User user = userService.getById(id);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        
        user.setStatus(status);
        boolean success = userService.updateById(user);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "USER_STATUS_UPDATE",
                "更新用户状态: " + id + ", 状态: " + status,
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(result);
    }
    
    @PostMapping("/{userId}/roles/{roleId}")
    @PreAuthorize("hasAuthority('user:edit')")
    public ResponseEntity<Map<String, Object>> assignRole(
            @PathVariable Long userId,
            @PathVariable Long roleId,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        boolean success = userService.assignRole(userId, roleId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "USER_ROLE_ASSIGN",
                "为用户分配角色: 用户ID=" + userId + ", 角色ID=" + roleId,
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(result);
    }
    
    @DeleteMapping("/{userId}/roles/{roleId}")
    @PreAuthorize("hasAuthority('user:edit')")
    public ResponseEntity<Map<String, Object>> removeRole(
            @PathVariable Long userId,
            @PathVariable Long roleId,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        boolean success = userService.removeRole(userId, roleId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "USER_ROLE_REMOVE",
                "移除用户角色: 用户ID=" + userId + ", 角色ID=" + roleId,
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(result);
    }
} 